package com.etang.a2020a1018;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bizideal.smarthome.socket.SocketClient;
import com.etang.a2020a1018.fragment.BarActivity;
import com.etang.a2020a1018.tools.CodeView;
import com.etang.a2020a1018.tools.DiyToast;
import com.etang.a2020a1018.tools.MyDataBaseHelper;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private MyDataBaseHelper dbHelper;
    private SQLiteDatabase db;
    private SharedPreferences sharedPreferences;
    private LinearLayout ll_login, ll_ip;
    private Button btn_login, btn_ip_con;
    private EditText et_user, et_pass, et_ip;
    private RadioButton ra_ip, ra_login;
    private CheckBox cb_rember, cb_autologin;
    private TextView tv_time, tv_sx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        init_check_frist();
        et_ip.setText(sharedPreferences.getString("ip", null));
        btn_ip_con.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_ip.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "请输入IP地址");
                } else {
                    DiyToast.showToast(getApplicationContext(), "设置成功");
                    sharedPreferences.edit().putString("ip", et_ip.getText().toString()).commit();
                }
            }
        });
        ra_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_ip.setVisibility(View.GONE);
                ll_login.setVisibility(View.VISIBLE);
            }
        });
        ra_ip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_ip.setVisibility(View.VISIBLE);
                ll_login.setVisibility(View.GONE);
            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_user.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "用户名不能为空");
                } else if (et_pass.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "密码不能为空");
                } else {
                    Cursor cursor = db.rawQuery("select * from user where username = ? and passward = ?", new String[]{et_user.getText().toString(), et_pass.getText().toString()});
                    if (cursor.moveToNext()) {
                        if (cb_autologin.isChecked()) {
                            sharedPreferences.edit().putBoolean("autologin", true)
                                    .putBoolean("rember", true)
                                    .putString("user", et_user.getText().toString())
                                    .putString("pass", et_pass.getText().toString())
                                    .commit();
                        } else if (cb_rember.isChecked()) {
                            sharedPreferences.edit().putBoolean("autologin", false)
                                    .putBoolean("rember", true)
                                    .putString("user", et_user.getText().toString())
                                    .putString("pass", et_pass.getText().toString())
                                    .commit();
                        } else {
                            sharedPreferences.edit().putBoolean("autologin", false)
                                    .putBoolean("rember", false)
                                    .putString("user", et_user.getText().toString())
                                    .putString("pass", et_pass.getText().toString())
                                    .commit();
                        }
                        SocketClient.ip = et_ip.getText().toString();
                        show_code_pass();
                    } else {
                        DiyToast.showToast(getApplicationContext(), "用户名或密码输入错误");
                    }
                }
            }
        });
        handler.post(time);
    }


    private void show_code_pass() {
        final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_codepass, null, false);
        alertDialog.setView(view);
        Button btn_con = (Button) view.findViewById(R.id.vtn_code_con);
        final EditText et_code = (EditText) view.findViewById(R.id.et_code_pass);
        final ImageView iv_show_code = (ImageView) view.findViewById(R.id.iv_code_show);
        iv_show_code.setImageBitmap(CodeView.createBitmap());
        iv_show_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_show_code.setImageBitmap(CodeView.createBitmap());
            }
        });
        btn_con.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_code.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "请输入IP地址");
                } else {
                    if (et_code.getText().toString().equalsIgnoreCase(CodeView.code)) {
                        alertDialog.dismiss();
                        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("正在登陆，请稍等");
                        progressDialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(3000);
                                } catch (Exception e) {

                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.dismiss();
                                        startActivity(new Intent(getApplicationContext(), BarActivity.class));
                                        finish();
                                    }
                                });
                            }
                        }).start();
                    } else {
                        DiyToast.showToast(getApplicationContext(), "验证码输入错误");
                    }
                }
            }
        });
        alertDialog.show();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            tv_time.setText(simpleDateFormat.format(new Date()));
            handler.postDelayed(time, 1000);
        }
    };
    Runnable time = new Runnable() {
        @Override
        public void run() {
            Message message = handler.obtainMessage();
            handler.sendMessage(message);
        }
    };

    private void init_check_frist() {
        if (sharedPreferences.getBoolean("is", false) == true) {
            if (sharedPreferences.getBoolean("rember", false) == true) {
                cb_rember.setChecked(true);
                et_user.setText(sharedPreferences.getString("user", null));
                et_ip.setText(sharedPreferences.getString("ip", null));
                et_pass.setText(sharedPreferences.getString("pass", null));
            }
            if (sharedPreferences.getBoolean("autologin", false) == true) {
                SocketClient.ip = sharedPreferences.getString("ip", null);
                startActivity(new Intent(getApplicationContext(), BarActivity.class));
                finish();
            }
        } else {
            sharedPreferences.edit().putBoolean("is", true).commit();
            sharedPreferences.edit().putString("ip", "18.1.10.1").commit();
            sharedPreferences.edit().putString("smo_value", "100").commit();
            sharedPreferences.edit().putString("temp_max", "26").commit();
            sharedPreferences.edit().putString("temp_low", "18").commit();
            sharedPreferences.edit().putString("ill_max", "300").commit();
            sharedPreferences.edit().putString("ill_low", "200").commit();
            sharedPreferences.edit().putString("co_max", "1000").commit();
            sharedPreferences.edit().putString("co_low", "1000").commit();
            sharedPreferences.edit().putString("per_value", "5").commit();
            sharedPreferences.edit().putString("smo_state", "开").commit();
            sharedPreferences.edit().putString("ill_state", "开").commit();
            sharedPreferences.edit().putString("temp_state", "开").commit();
            sharedPreferences.edit().putString("co_state", "开").commit();
            sharedPreferences.edit().putString("per_state", "开").commit();
        }
    }

    private void initView() {
        sharedPreferences = getSharedPreferences("rember", MODE_PRIVATE);
        dbHelper = new MyDataBaseHelper(getApplicationContext(), "info.db", null, 2);
        db = dbHelper.getWritableDatabase();
        btn_ip_con = (Button) findViewById(R.id.btn_ip_con);
        btn_login = (Button) findViewById(R.id.btn_login);
        et_pass = (EditText) findViewById(R.id.et_pass);
        et_ip = (EditText) findViewById(R.id.et_ip);
        et_user = (EditText) findViewById(R.id.et_user);
        ra_ip = (RadioButton) findViewById(R.id.ra_ip);
        ra_login = (RadioButton) findViewById(R.id.ra_login);
        ll_login = (LinearLayout) findViewById(R.id.ll_login);
        ll_ip = (LinearLayout) findViewById(R.id.ll_ip);
        cb_autologin = (CheckBox) findViewById(R.id.cb_autologin);
        cb_rember = (CheckBox) findViewById(R.id.cb_rember);
        tv_sx = (TextView) findViewById(R.id.tv_time_sx);
        tv_time = (TextView) findViewById(R.id.tv_time);
    }
}